#include "stdafx.h"
#include "syscfg.h"
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdarg.h>
#include "sysdebug.h"
#include "Comm.h"
#include "sysfs.h"
#include "ComAPI.h"
#include "sysapi.h"
#ifdef SYS_LINUX
#include <syslog.h>
#endif

#define DEBUG_FILE_SIZE (2 * 1024 * 1024)
#define DB_BUF_LEN  (1024 * 16)

//#define DebugOUT(s, len)   do { syslog(LOG_INFO, s);} while(0)
//#define SDebug(debug, s, len)   do { if(IsDebugOn(debug)) {syslog(LOG_INFO, s);}} while(0)

#define DebugOUT(s, len)   do { printf((char* )s); } while (0)
//#define STRACE(debug, s, len)   do { if(IsDebugOn(debug)) {printf((char* )s);}} while(0)
bool DebugOutLoopFile(char* pszPathName, BYTE* pbData, DWORD dwLen, DWORD dwTotalLen);

OS_SEM g_semDebug;
//BYTE* g_pbDbItem;
DWORD g_dwDebugClick;
bool g_fDbInited = false;
bool g_fDebugEnable = true;

BYTE g_bDbBuf[DB_BUF_LEN];  //ʹ�ù�����������ÿ���̶߳������ô��Ķ�ջ

//����:��ʼ����ͬϵͳ�µ�����Ͳ�Ĳ���
bool SysInitDebug()
{
    g_semDebug = OSSemCreate(1);

    g_dwDebugClick = GetClick();

#ifdef COMM_DEBUG
    //g_commDebug.Open(COMM_DEBUG, CBR_115200, 8, ONESTOPBIT, NOPARITY);
#endif
/*
   #ifdef SYS_LINUX
    openlog("Friendcom :", LOG_PID | LOG_NDELAY, LOG_LOCAL2);
    setlogmask(LOG_UPTO(LOG_INFO));
   #endif
 */
    return true;
}

bool InitDebug()
{
    //TDataItem di = GetItemEx(BN1, PN0, 0x1002);  //0x1002 16 ����ĵ����������

    //g_pbDbItem = di.pbAddr;

    //g_fDbInited = true;

    //BYTE flag = g_pbDbItem[0];
    //if ((flag & 0x01) == 0)    //������������Ϣ
    //{
    //   g_fDebugEnable = false;
    //}

    return true;
}

bool IsDebugOn(BYTE bType)
{
    if (!g_fDebugEnable) //���ڱ���ͨѶ�ں͵���������ص������,ʹ�ñ��ӿ�������
    {
        return false;
    }

    return true;
}

// ��ݸ�����ӡ�����򿪴�ӡ����
bool DebugEnable(BYTE bType)
{
	if (!g_fDebugEnable) //���ڱ���ͨѶ�ں͵���������ص������,ʹ�ñ��ӿ�������
	{
		return false;
	}


	return true;
}


void debug_printf( const char *fmt, ... )
{
    WORD wOffset = 0;
    TTime tmTime;

    GetSysTime(&tmTime);

    OSSemPend(g_semDebug);

    sprintf((char*)g_bDbBuf, "%02d%02d%02d%02d ", (BYTE )tmTime.nDay, (BYTE )tmTime.nHour, (BYTE )tmTime.nMinute, (BYTE )tmTime.nSecond);
    wOffset = strlen((char*)g_bDbBuf);

    va_list varg;

    va_start(varg, fmt );
    vsprintf((char* )g_bDbBuf + wOffset, fmt, varg);
    va_end(varg);

    WORD wLen = strlen((char* )g_bDbBuf);
    //DebugOutLoopFile((char *)USER_DATA_PATH "Debug.inf", (BYTE*)g_bDbBuf, wLen, DEBUG_FILE_SIZE);

    if (IsConsoleClosed())
    {
        OSSemPost(g_semDebug);
        return;
    }

    DebugOUT((char*)g_bDbBuf, wLen);

    OSSemPost(g_semDebug);
}

void STRACE(WORD debug, char *s, WORD len)
{
    if (IsDebugOn(debug))
    {
        //DebugOutLoopFile((char *)USER_DATA_PATH "Debug.inf", (BYTE*)s, len, DEBUG_FILE_SIZE);

        if (IsConsoleClosed())
        {
            return;
        }
        printf((char* )s);
    }
}

WORD PrintBuf(BYTE* out, BYTE* in, WORD wInLen)
{
    for (int i = 0; i < wInLen; i++)
    {
        BYTE b = *in++;
        BYTE hi = b >> 4;
        BYTE lo = b & 0x0f;
        *out++ = ' ';
        if (hi >= 0x0a)
        {
            *out++ = hi - 0x0a + 'A';
        }
        else
        {
            *out++ = hi + '0';
        }

        if (lo >= 0x0a)
        {
            *out++ = lo - 0x0a + 'A';
        }
        else
        {
            *out++ = lo + '0';
        }
    }

    *out++ = 0;
    return wInLen * 3;
}

WORD PrintBuf(BYTE* out, WORD wOutLen, BYTE* in, WORD wInLen)
{
    WORD i;

    for (i = 0; i < wInLen; i++)
    {
        if ((i + 1) * 3 > wOutLen)
        {
            return i;
        }

        BYTE b = *in++;
        BYTE hi = b >> 4;
        BYTE lo = b & 0x0f;
        *out++ = ' ';
        if (hi >= 0x0a)
        {
            *out++ = hi - 0x0a + 'A';
        }
        else
        {
            *out++ = hi + '0';
        }

        if (lo >= 0x0a)
        {
            *out++ = lo - 0x0a + 'A';
        }
        else
        {
            *out++ = lo + '0';
        }
    }

    return i;
}

void DebugBuf(WORD wSwitch, char* szHeadStr, BYTE* p, WORD wLen)
{
    WORD wOffset = 0;
    TTime tmTime;

    GetSysTime(&tmTime);

    OSSemPend(g_semDebug);
    sprintf((char*)g_bDbBuf, "%02d%02d%02d%02d ", (BYTE )tmTime.nDay, (BYTE )tmTime.nHour, (BYTE )tmTime.nMinute, (BYTE )tmTime.nSecond);
    wOffset = strlen((char*)g_bDbBuf );

    WORD wStrLen = strlen(szHeadStr) + wOffset;
    memcpy(g_bDbBuf + wOffset, szHeadStr, wStrLen);

    for (WORD wPrinted = 0; wPrinted < wLen; )
    {
        WORD n = PrintBuf(&g_bDbBuf[wStrLen], 1000 - wStrLen, p, wLen - wPrinted);
        p += n;
        wPrinted += n;
        wStrLen += n * 3;
        if (n == 0 || wStrLen > 1000)   //�Ѿ���bBuf[]��������,���Ȱѵ�ǰ��������
        {
            g_bDbBuf[wStrLen++] = '\r';
            g_bDbBuf[wStrLen++] = '\n';
            g_bDbBuf[wStrLen++] = 0;
            STRACE(wSwitch, (char*)g_bDbBuf, wStrLen);
            wStrLen = 0;
        }
    }

    if (wStrLen > 0)
    {
        g_bDbBuf[wStrLen++] = '\r';
        g_bDbBuf[wStrLen++] = '\n';
        g_bDbBuf[wStrLen++] = 0;
        STRACE(wSwitch, (char*)g_bDbBuf, wStrLen);
    }

    OSSemPost(g_semDebug);
}

void DebugFrm(char* pszHeader, BYTE* pbBuf, WORD wLen)
{
    if (wLen > 0)
    {
        char szBuf[64];
        sprintf(szBuf, "%s %d\n", pszHeader, wLen);
        DebugBuf(DEBUG_CRITICAL, szBuf, pbBuf, wLen);
    }
}
/*
   void Debug(WORD debug, char *p)
   {
    if (IsDebugOn(debug))
        debug_printf(p);
   }
 */

//����:���ڱ���ͨѶ�ں͵���������ص������,ʹ�ñ��ӿ�������
void EnableDebug(bool fEnable)
{
    g_fDebugEnable = fEnable;
    //BYTE bBuf[256];
    //ReadItemEx(BN1, PN0, 0x1002, bBuf);  //0x1002 16 ����ĵ����������
    //bBuf[0] &= 0xFE;
    //bBuf[0] |= fEnable ? 0x01 : 0;
    //WriteItemEx(BN1, PN0, 0x1002, bBuf);
}

bool IsDebugEnable()
{
    return g_fDebugEnable;
}


bool DebugOutLoopFile(char* pszPathName, BYTE* pbData, DWORD dwLen, DWORD dwTotalLen)
{
	return false;

    bool fRet = true;
    int fp = open(pszPathName, O_CREAT | O_RDWR | O_BINARY, S_IREAD | S_IWRITE);

    //windows�±���ʹ��O_BINARY,����������ĳ���Ϊ��,����ϵͳ��O_BINARYΪ��

    if (fp < 0)
    {
        //Debug(DB_GLOBAL, ("WriteFile err!! fail to open %s.\r\n", pszPathName));
        return false;
    }
    else
    {
        //int nFileSize = fseek(fp, 0, SEEK_END);
        lseek(fp, 0, SEEK_SET);
        DWORD dwFileCurPos = 0;
        read(fp, (BYTE*)&dwFileCurPos, 4);

        if (dwFileCurPos > dwTotalLen)
        {
            dwFileCurPos = 4;
        }

        lseek(fp, dwFileCurPos, SEEK_SET);
        ssize_t retLen = write(fp, pbData, dwLen);
        if (retLen<0 || (DWORD)retLen!=dwLen)
        {
            //Debug(DB_GLOBAL, ("WriteFile err!  fail to write %s .\r\n", pszPathName));
            fRet = false;
        }

        lseek(fp, 0, SEEK_SET);
        dwFileCurPos += dwLen;
        write(fp, (BYTE*)&dwFileCurPos, 4);
    }
    close(fp);

    return fRet;
}
